import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import Element from "element-ui";
import axios from "axios";
import VueBus from './event-bus'
Vue.use(VueBus);
import Avue from "@smallwei/avue";
import "@smallwei/avue/lib/index.css";
Vue.use(Avue);
// 主题样式
import "@/assets/theme/index.css";
import '../public/libs/dialogDrag/dialogDrag.js'
import {
    createCustomfield,
    updateContent,
} from "@/api/customField.js";
import {
    createForm,
    formUpdateContent
} from "@/api/formWork.js";

// 全局css样式
import "@/styles/index.scss";

// 引入store
import store from "./store";


// 国际化
import i18n from "./lang";

import {
    selectUser,
} from "./api/userController";

Vue.prototype.$http = axios;
Vue.config.productionTip = false;
// Vue.prototype.$EventBus = new Vue()
// 使用Element UI
Vue.use(Element, {
    i18n: (key, value) => i18n.t(key, value)
});

Vue.use(Element);
new Vue({
    i18n,
    store,
    router,
    render: h => h(App)
}).$mount("#app");
/* eslint-disable no-new */
window.eventEmitter = new Vue();

//*************************页面公共接口数据请求处************************************************ */
import {
    roleList,
    userList,
    deptList,
    getThemeColor
} from '@/common/commonApi'
window.CONFIG.selectAllInfo = {}
new Promise(roleList).then(res => {
    window.CONFIG.selectAllInfo.roleList = res
    Vue.prototype.$appName = res
})
new Promise(deptList).then(res => {
    window.CONFIG.selectAllInfo.deptList = res
})
new Promise(userList).then(res => {
    window.CONFIG.selectAllInfo.userList = res
})

//*************************按钮赋值处********************************************************* */
import btnsAuth from '@/common/btnsAuth'
window.CONFIG.btnState = btnsAuth
let btnState = window.CONFIG.btnState
import {
    getBtnStateFun,
    makeForm,
    callEnd,
    EventAgentInfo,
    EventCallRecordChange,
    EventChatRecordChange,
    EventChatDone,
    EventAgentLogout,
    EventCusAndAccInfo,
    EventEditStatusWorkOrder,
    InterctClientInfo
} from './utils/getMessageFun'
// 初始化按钮状态
for (let i in btnState) {
    btnState[i] = ""
}
// 本地默认给初始值
if (window.CONFIG.test) {
    for (let i in btnState) {
        btnState[i] = true
    }
}

function readCookie (name) {
    var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else {
        return null;
    }
}
// store.state.userId = readCookie("userId");
// store.commit("userIdFun", readCookie("userId"));
// sessionStorage.setItem("userIds", readCookie("userId"));
// sessionStorage.setItem("tenantId", readCookie("tenantId"));
// selectUser(readCookie("userId")).then(res => {
//   if (res.data.retCode === 200) {
//     store.commit("userIdFun", res.data.data.id);
//   } else {
//     Element.Message({
//       type: "error",
//       message: res.data.msg
//     });
//   }
// });

function GetQueryString (name) {
    if (window.location.hash.split("?").length <= 1) {
        if (!readCookie("userId")) {
            return
        }
        getBtnStateFun(readCookie("userId"), readCookie("tenantId"), btnState)
        store.commit("agentIdFun", readCookie("userId")); // 创建人的id
        store.state.userId = readCookie("userId");
        sessionStorage.setItem("userIds", readCookie("userId"));
        sessionStorage.setItem("tenantId", readCookie("tenantId"));
        let id = readCookie("userId")
        selectUser(id).then(res => {
            if (res.data.retCode === 200) {
                store.commit("userIdFun", res.data.data.id);
            } else {
                Element.Message({
                    type: "error",
                    message: res.data.msg
                });
            }
        });
        return null;
    }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.hash.split("?")[1].match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
if (GetQueryString("userId")) {
    sessionStorage.setItem("userIds", GetQueryString("userId"));
    sessionStorage.setItem("tenantId", GetQueryString("tenantId"));
    // getBtnStateFun('test1007', 'default', btnState)
    getBtnStateFun(GetQueryString("userId"), GetQueryString("tenantId"), btnState)
    store.commit("agentIdFun", GetQueryString("userId")); // 创建人的id
    store.commit("userIdFun", GetQueryString("userId"));
    store.state.userId = GetQueryString("userId");
    sessionStorage.setItem("userIds", GetQueryString("userId"));
    let id = GetQueryString("userId")
    selectUser(id).then(res => {
        if (res.data.retCode === 200) {
            store.commit("userIdFun", res.data.data.id);
        } else {
            Element.Message({
                type: "error",
                message: res.data.msg
            });
        }
    });
}
// ********************************全局监听组件消息*********************************************** */
window.globalUiKit = window.globalUiKit || {}
window.globalUiKit.vm = new Vue();
// window.eventEmitter.$on('callEnd', obj => {
//   callEnd(obj)
// });
window.eventEmitter.$on('EventAgentInfo', obj => {
    EventAgentInfo(obj)
})
window.eventEmitter.$on('EventCallRecordChange', obj => {
    EventCallRecordChange(obj)

});
window.eventEmitter.$on('EventChatRecordChange', obj => {
    EventChatRecordChange(obj)
});
window.eventEmitter.$on('EventChatDone', obj => {
    EventChatDone(obj)
})
// EventAgentLogout  EventCallReleased  EventAfterCall 
window.eventEmitter.$on('EventAfterCall', obj => {
    EventAgentLogout(obj)
});
window.eventEmitter.$on('EventCusAndAccInfo', obj => {
    EventCusAndAccInfo(obj)
})
window.eventEmitter.$on('EventEditStatusWorkOrder', obj => {
    EventEditStatusWorkOrder(obj)
})
//*************************全局监听工作台postMessage事件****************************************** */
window.onmessage = function (messageEvent) {
    // console.log('biz receive post message info ' + JSON.stringify(messageEvent.data))
    let message = messageEvent.data;
    console.log('工单收到的消息：', message)
    if (!message) {
        return;
    }
    if (message.system === "makeForm") {
        makeForm(message)
    }
    // 客户唯一标识
    if (message.event === "InterctClientInfo") {
        InterctClientInfo(message.data)
    }
    // 结束会话的时候清空相对应客户唯一标识
    if (message.event === "callEnd") {
        callEnd('')
    }
    // 座席信息
    if (message.event === "EventAgentInfo") {
        EventAgentInfo(message.data.agentInfo)
    }
    //  电话页
    if (message.event === "EventCallRecordChange") {
        EventCallRecordChange(message.data)
    }
    // 在线页签切换
    if (message.event === "EventChatRecordChange") {
        console.log("postMessage收到的消息", message.data)
        EventChatRecordChange(message.data)
    }
    // 文本结束会话
    if (message.event === "EventChatDone") {
        EventChatDone(message)
    }
    // 电话结束会话       EventCallReleased
    if (message.event === "EventAfterCall") {
        EventAgentLogout(message)
    }
    // 业务系统客户信息、账户信息
    if (message.event === "EventCusAndAccInfo") {
        EventCusAndAccInfo(message.data)
    }
    // 监听工作台登出查询当前编辑中工单数量
    if (message.event === "EventEditStatusWorkOrder") {
        EventEditStatusWorkOrder()
    }
}
// 页面加载完成，给工作台发送完成指令 修改
window.onload = function () {
    if (window.parent.parent) {
        window.parent.parent.postMessage({
            event: 'EventDomLoaded'
        }, '*')
    } else if (window.parent) {
        window.parent.postMessage({
            event: 'EventDomLoaded'
        }, '*')
    }
    // window.eventEmitter.$emit('EventDomLoaded', {})
    // if (window.parent.parent) {
    //   window.parent.parent.postMessage({
    //       event: "EventDomLoaded"
    //       // data: {
    //       //     load: 'Y'
    //       // }
    //     },
    //     "*"
    //   );
    // }
};
//*************************全局监听form表单的postMessage事件************************************** */
window.eventEmitter.$on("EventPlatform2KBP", res => {
    let data = JSON.parse(sessionStorage.getItem("form"));
    console.log("state:" + store.state.userId)
    if (res.type === 1 && res.option === 2) {
        let params = {
            userId: store.state.userId,
            content: res.widgetForm,
            id: store.state.formWorkId,
            name: res.formName
        };
        formUpdateContent(params).then(res => {
            if (res.data.retCode === 200) {
                Element.Message({
                    message: res.data.msg,
                    type: "success"
                });
                router.push("/formWork");
            } else {
                Element.Message({
                    message: res.data.msg,
                    type: "error"
                });
            }
        });
    } else if (res.type === 1 && res.option === 1) {
        let params = {
            content: res.widgetForm,
            name: res.formName,
            userId: store.state.userId
        };
        createForm(params).then(res => {
            if (res.data.retCode === 200) {
                Element.Message({
                    message: res.data.msg,
                    type: "success"
                });
                router.push("/formWork");
            } else {
                Element.Message({
                    message: res.data.msg,
                    type: "error"
                });
            }
        });
    } else if (res.type === 1 && res.option === 3) {
        let params = {
            content: res.widgetForm,
            name: res.formName,
            userId: store.state.userId
        };
        createForm(params).then(res => {
            if (res.data.retCode === 200) {
                Element.Message({
                    message: res.data.msg,
                    type: "success"
                });
                router.push("/formWork");
            } else {
                Element.Message({
                    message: res.data.msg,
                    type: "error"
                });
            }
        });
    } else if (res.type === 2 && res.option === 1) {
        let params = {
            userId: store.state.userId,
            content: res.widgetForm
        };
        createCustomfield(params).then(res => {
            if (res.data.retCode === 200) {
                Element.Message({
                    message: res.data.msg,
                    type: "success"
                });
                router.push("/customField");
            } else {
                Element.Message({
                    message: res.data.msg,
                    type: "error"
                });
            }
        });
    } else if (res.type === 2 && res.option === 2) {
        let params = {
            userId: store.state.userId,
            content: res.widgetForm,
            id: store.state.customFieldId,
            name: res.widgetForm.list[0].name
        };
        updateContent(params).then(res => {
            if (res.data.retCode === 200) {
                Element.Message({
                    message: res.data.msg,
                    type: "success"
                });
                router.push("/customField");
            } else {
                Element.Message({
                    message: res.data.msg,
                    type: "error"
                });
            }
        });
    }
    sessionStorage.setItem("form", JSON.stringify(data));
});